<?php
namespace yuankezhan\htmlHelper\options;

use yuankezhan\htmlHelper\Utils;
use ReflectionClass;

class BaseObject
{
    public function __construct($array = [])
    {
        $this->_instantiateObject($array);
    }

    private function _instantiateObject($array)
    {
        foreach ($array as $key => $val)
        {
            if (property_exists($this, $key))
            {
                $className = Utils::rootNameSpace() . "\options\\" . ucfirst($key);
                $this->{$key} = class_exists($className) ? new ($className)($val) : $val;
            }
        }
    }

    /**
     * 设置类的成员属性
     * @param array $array
     * @return static
     */
    public static function set(array $array)
    {
        // self指向定义了当前被调用方法的类， static指向调用当前静态方法的类。
        return new static($array);
    }

    // toArray 排除项
    public function toArrayExcept()
    {
        return [];
    }

    /**
     * 当前对象转换成数组
     * @return array
     */
    public function toArray()
    {
        $object = (new ReflectionClass($this))->getProperties();
        $data = [];
        foreach ($object as $o)
        {
            $dataKey = $o->name;
            $key = $o->name;
            if (!in_array($key, $this->toArrayExcept()) && $this->{$key} !== null)
            {
                $data[$dataKey] = $this->{$key};
            }
        }
        return $data;
    }
}